const highlight_keys = ["pnl_net", "pnl_hold", "changerate"];
const HIGHLIGHT = {
  RED: "red",
  GREEN: "green",
  DEFAULT: "",
};
const formate_keys = ["changerate"];

function parsePnlResponse(rsp) {
  const result = { titles: [], columns: [] };
  try {
    const columns = [];
    const data = JSON.parse(rsp.data);
    const items = Object.values(data);
    const entries = Object.entries(data);
    for (const k in items[0]) {
      let tmp = {};
      for (const [t_k, t_v] of entries) {
        tmp = { ...tmp, [t_k]: t_v[k] };
      }
      columns.push(tmp);
    }
    const titles = Object.keys(data).map((item) => ({
      label: item,
      value: item,
    }));
    Object.assign(result, { titles, columns });
  } catch (e) {
    console.error(e);
  }
  return result;
}

function getCellStyle(row, column) {
  const label = column.label;
  if (highlight_keys.includes(label)) {
    const cellVal = parseFloat(row[label]);
    const color = getHighlightColor(cellVal);
    return { color };
  }
  return {};
}

function parseNumber(column, cellValue) {
  return formate_keys.includes(column.label)
    ? parseFloat(cellValue * 100 + "").toFixed(2) + "%"
    : cellValue + "";
}

/**
 * 重置 stdcode 排序规则
 * @param {*} title
 * @returns
 */
function sortStdCode(title) {
  return (objA, objB) => {
    let sortValA = objA[title];
    let sortValB = objB[title];
    if (title === "stdcode") {
      sortValA = sortValA.split(".").pop();
      sortValB = sortValB.split(".").pop();
    }
    let sortIndex = 0;
    if (sortValA > sortValB) {
      sortIndex = 1;
    } else if (sortValA < sortValB) {
      sortIndex = -1;
    } else {
      sortIndex = 0;
    }
    return sortIndex;
  };
}

function getHighlightColor(val) {
  return val > 0
    ? HIGHLIGHT.RED
    : val < 0
    ? HIGHLIGHT.GREEN
    : HIGHLIGHT.DEFAULT;
}

export { getCellStyle, parseNumber, sortStdCode, parsePnlResponse };
